<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header
        :content="id ? '编辑月卡' : '添加月卡'"
        @back="$router.back()"
      />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <!-- car form -->
        <div class="form">
          <el-form
            ref="carForm"
            label-width="100px"
            :model="carForm"
            :rules="rules"
          >
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carForm.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carForm.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <!-- card form -->
        <div class="form">
          <el-form
            ref="cardForm"
            label-width="100px"
            :model="cardForm"
            :rules="rules"
          >
            <el-form-item label="有效日期" prop="cardTime">
              <el-date-picker
                v-model="cardForm.cardTime"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model.number="cardForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="cardForm.paymentMethod" clearable>
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="addMonthCard">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import {
  addMonthCardAPI,
  getCardDetailAPI,
  editCardDetailAPI,
  deleteCardAPI
} from '@/api/card'
export default {
  name: 'AddMonthCard',
  data () {
    return {
      carForm: {
        personName: '',
        phoneNumber: '',
        carNumber: '',
        carBrand: ''
      },
      cardForm: {
        // cardStartDate: "",
        // cardEndDate: "",
        cardTime: [],
        paymentAmount: '',
        paymentMethod: ''
      },
      rules: {
        personName: [
          { required: true, message: '请输入车主名称', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            // 知识点：elm ui 可以直接使用正则校验字段，记住这个用法
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        carNumber: [
          { required: true, message: '请输入车辆号码', trigger: 'blur' },
          {
            pattern:
              /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
            message: '请输入正确的车辆号码',
            trigger: 'blur'
          }
        ],
        carBrand: [
          { required: true, message: '请输入车辆品牌', trigger: 'blur' }
        ],
        cardTime: [{ required: true, message: '请输入日期', trigger: 'blur' }],
        paymentAmount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字值' }
        ],
        paymentMethod: [
          {
            required: true,
            message: '请输入支付方式',
            trigger: 'change'
          }
        ]
      },
      options: [
        { value: 'Alipay', label: '支付宝' },
        { value: 'WeChat', label: '微信' },
        { value: 'Cash', label: '线下' }
      ]
    }
  },
  created () {
    if (this.id) {
      this.renderData()
    }
  },
  methods: {
    async addMonthCard () {
      // 表单校验
      // this.$refs["carForm"].validate((pass) => {
      //   if (!pass) return;
      // });
      // this.$refs["cardForm"].validate((pass) => {
      //   if (!pass) return;
      // });
      // 知识点：elm ui 的表单校验方法是异步的，如果用注释里的写法，校验失败还
      // 会往下执行发送请求
      const carValid = await this.$refs.carForm.validate()
      if (!carValid) return
      const cardValid = await this.$refs['cardForm'].validate()
      if (!cardValid) return

      const data = {
        ...this.carForm,
        ...this.cardForm,
        cardStartDate: this.cardForm.cardTime[0],
        cardEndDate: this.cardForm.cardTime[1]
      }
      delete data.cardTime

      if (this.id) {
        await editCardDetailAPI(data)
        this.$message.success('编辑月卡成功')
      } else {
        await addMonthCardAPI(data)
        this.$message.success('添加月卡成功')
      }
      // 知识点：路由跳转的一些常见方法，比如返回上下页，go(-1),注意下这些用法就行
      this.$router.back()
    },
    resetForm () {
      this.$refs.cardForm.resetFields()
      this.$refs.carForm.resetFields()
    },
    // 数据回显
    async renderData () {
      const { data } = await getCardDetailAPI(this.id)
      // console.log(data)

      const {
        personName,
        phoneNumber,
        carNumber,
        carBrand,
        rechargeId,
        carInfoId
      } = data
      const { cardStartDate, cardEndDate, paymentAmount, paymentMethod } = data
      ;(this.carForm = {
        personName,
        phoneNumber,
        carNumber,
        carBrand,
        carInfoId
      }),
        (this.cardForm = {
          cardTime: [cardStartDate, cardEndDate],
          paymentAmount,
          paymentMethod,
          rechargeId
        })
    }
  },
  computed: {
    // 知识点：常用的属性可以写成计算属性，方便复用
    id () {
      return this.$route.query.id
    }
  }
}
</script>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
  // 重写eleui的样式
  ::v-deep .el-date-editor .el-range-separator {
    width: 7%;
  }
  ::v-deep .el-input__inner {
    min-width: 350px; /* 设置最小宽度 */
  }
}
</style>
